package com.ctyon.watchsdk.task;


import android.util.Log;

import com.ctyon.watchsdk.callback.WatchMsgCallback;
import com.ctyon.watchsdk.client.Client;
import com.ctyon.watchsdk.client.ClientMessage;
import com.ctyon.watchsdk.config.Option;
import com.ctyon.watchsdk.protobuf.WatchMessage;

import io.netty.channel.Channel;


/**
 * Created by Lee on 2019/5/24.
 */

public class WatchTask {

    private static final String TAG = "NettyTask";

    private WatchMsgCallback msgCallback;
    private Channel clientChannel;
    private Client client;
    private Option option;

    public WatchTask() {
    }

    public void init(Option option){
        this.option = option;
        if (null == client){
            client = new Client();
            client.init(option.getPingInterval(), option.getReConnectInterval());
        }
    }

    public void reConnect(){
        Log.d(TAG, "客户端重连 ... ");
        client.connect();
    }

    private static class NettyTaskHolder {

        private static final WatchTask INSTANCE = new WatchTask();

    }

    public static final WatchTask getInstance() {

        return NettyTaskHolder.INSTANCE;

    }

    public Option getOption() {
        return option;
    }

    public void setClientChannel(Channel clientChannel) {
        this.clientChannel = clientChannel;
    }

    public void setMsgCallback(WatchMsgCallback msgCallback) {
        this.msgCallback = msgCallback;
    }

    public boolean isClientAlive() {
        return clientChannel == null ? false : (clientChannel.isOpen() && clientChannel.isActive());
    }

    public void releaseChannel() {
        if (null != clientChannel) {
            clientChannel.close();
        }
    }

    public void callbackPeng() {
        if (null != msgCallback) {
            msgCallback.peng();
        }
    }

    public void callbackTimeOut() {
        if (null != msgCallback) {
            msgCallback.onTimeOut();
        }
    }

    public void callbackFeed(String cmd) {
        if (null != msgCallback) {
            msgCallback.feed(cmd);
        }
    }

    public void callbackUnknownMsg(Object msg) {
        if (null != msgCallback) {
            msgCallback.unknowMsg(msg);
        }
    }

    public void callbackReceive(ClientMessage msg) {
        if (null != msgCallback) {
            msgCallback.receiveMsg(msg);
        }
    }


    /**
     * -------------------------------------------------- 消息 --------------------------------------
     */
    public void sendNettyMsg(WatchMessage.Msg msg) {
        if (isClientAlive()) {
            Log.d(TAG, "sendNettyMsg : " + msg.toString());
            clientChannel.writeAndFlush(msg);
        }
    }


}
